import {
    createRouter,
    createWebHashHistory
} from "vue-router";
import {
    error
} from "@/utils/message";
let map = new Map([
    ['/', '登录'],
    ['/home', '首页'],
    ['/welcome', '欢迎页'],
    ['/users', '用户列表'],
    ['/roles', '角色列表'],
    ['/rights', '权限列表'],
    ['/goods', '商品列表'],
    ['/GoodsAdd', '商品添加'],
    ['/params', '分类参数'],
    ['/categories', '商品分类'],
    ['/orders', '订单列表'],
    ['/reports', '数据报表'],
    ['/404', '404'],
]);
const routes = [{
        path: '/',
        component: () => import("@/components/Login.vue")
    },
    {
        path: '/home',
        component: () => import("@/components/Home.vue"),
        redirect: '/welcome',
        children: [{
                path: '/welcome',
                component: () => import("@/components/Welcome.vue")
            },
            {
                path: '/users',
                component: () => import("@/components/Users.vue")
            },
            {
                path: '/roles',
                component: () => import("@/components/Roles.vue")
            },
            {
                path: '/rights',
                component: () => import("@/components/Rights.vue")
            },
            {
                path: '/goods',
                component: () => import("@/components/Goods.vue")
            },
            {
                path: '/goodsAdd',
                component: () => import("@/components/GoodsAdd.vue")
            },
            {
                path: '/params',
                component: () => import("@/components/Params.vue")
            },
            {
                path: '/categories',
                component: () => import("@/components/Categories.vue")
            },
            {
                path: '/orders',
                component: () => import("@/components/Orders.vue")
            },
            {
                path: '/reports',
                component: () => import("@/components/Reports.vue")
            },
        ],
    }, {
        path: '/404',
        component: () => import("@/components/Page404.vue")
    },
    {
        path: '/:catchAll(.*)',
        redirect: '/404',
    },
]
const router = createRouter({
    history: createWebHashHistory(),
    routes,
})
router.beforeEach((to, from, next) => {
    let toPath = to.path
    // 设置标题
    document.title = map.get(toPath)
    if (toPath === '/') {
        // 登录和注册放行
        return next()
    }
    // 判断用户是否登录
    let str = sessionStorage.getItem('user-login')
    if (!str) {
        error('请先登录！')
        return next('/')
    }
    let token = JSON.parse(str).data.token
    if (!token) {
        error('请先登录！')
        return next('/')
    }
    next()
})
export default router